package com.amazon.shop.filter.globalwebfilter;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 
 * 创建时间：2019年9月7日 上午10:56:49
 * 
 * 项目名称：rebatencenter
 * 
 * @author wanglong
 * 
 * @version 1.0
 * 
 * @since JDK 1.8.0_171
 * 
 *        文件名称：WebUtil.java
 * 
 *        类说明：
 *
 *        Modification History: Date Author Version Description
 *        ---------------------------------------------------------*
 */
public class WebUtil {

	private static AtomicLong lastId = new AtomicLong();// 自增id，用于requestId的生成过程
	private static final long startTimeStamp = System.currentTimeMillis();
	// 启动加载时的时间戳，用于requestId的生成过程
	private static final String ip = getLocalAddress();// 本机ip地址，用于requestId的生成过程

	public static void main(String[] args) {
		System.out.println(hexIp(ip));
		System.out.println(resolveReqId());
	}

	public static String resolveReqId() {
		// 规则： hexIp(ip)base36(timestamp)-seq
		return hexIp(ip) +"-"+ Long.toString(startTimeStamp, Character.MAX_RADIX) + "-" + lastId.incrementAndGet();
	}

	// 将ip转换为定长8个字符的16进制表示形式：255.255.255.255 -> FFFFFFFF
	private static String hexIp(String ip) {
		StringBuilder sb = new StringBuilder();
		for (String seg : ip.split("\\.")) {
			String h = Integer.toHexString(Integer.parseInt(seg));
			if (h.length() == 1) {
				sb.append("0");
			}
			sb.append(h);
		}
		return sb.toString();
	}

	public static String getLocalAddress() {
		String ip = "";
		try {
			ip = InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ip;
	}

	public static String getRequestIp() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		String remoteIp = request.getHeader("x-forwarded-for");
		if (remoteIp == null || remoteIp.length() == 0 || remoteIp.equalsIgnoreCase("unknown")) {
			remoteIp = request.getHeader("Proxy-Client-IP");
			if (remoteIp == null || remoteIp.length() == 0 || remoteIp.equalsIgnoreCase("unknown")) {
				remoteIp = request.getHeader("WL-Proxy-Client-IP");
				if (remoteIp == null || remoteIp.length() == 0 || remoteIp.equalsIgnoreCase("unknown")) {
					remoteIp = request.getRemoteAddr();
				}
			}
		}
		return remoteIp;
	}
}
